package vip.xiaomoli.courier.component.timewheel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vip.xiaomoli.courier.util.CourierUtil;

class TaskSlotWheel {

	private static final Logger LOG = LoggerFactory.getLogger(TaskSlotWheel.class);

	private static final int SLOT_NUM = 3600;

	private final TaskSlot[] taskSlots;

	TaskSlotWheel() {
		taskSlots = new TaskSlot[SLOT_NUM];
		for (int i = 0; i < SLOT_NUM; i++) {
			this.taskSlots[i] = new TaskSlot();
		}
	}
	
	void add(CourierTask task, int delaySeconds) {
		if (delaySeconds <= 0) delaySeconds = 1; // 最少延迟1秒，以免此秒内的tasks加载已经完成而得不到执行
		int slotIndex = (CourierUtil.getCurrentSecondInHour() + delaySeconds) % SLOT_NUM;
		task.setCycleNum(delaySeconds / SLOT_NUM);
		taskSlots[slotIndex].addTask(task);
		LOG.debug("Add task，task={}, slotIndex={}", task.toString(), slotIndex);
	}

	TaskSlot pick(int index) {
		return taskSlots[index];
	}

}
